var uuid = {
	nums:['0','1','2','3','4','5','6','7','8','9'],
	chars:['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
	getRandomNum:function(Min, Max) {   
		var Range = Max - Min;   
		var Rand = Math.random();   
		return(Min + Math.round(Rand * Range));   
	},
	create:function() {
		var numslen = this.nums.length - 1;
		var charslen = this.chars.length - 1;
		var id = "";
		for(var i=0; i<40; i++) {
			id += this.chars[this.getRandomNum(0, charslen)];
		}
		for(var i=0; i<10; i++) {
			id += this.nums[this.getRandomNum(0, numslen)];
		}
		return id;
	}
};
/**
 * 桌面
 */
(function($, isRoot) {
	//高版本jquery，需要使用传统的方式浅层进行序列化，来适应jsp
	$.ajaxSettings.traditional = true;
	//去掉分页数字下拉列表
	$.fn.pagination.defaults.showPageList = false;
	
	Array.prototype.indexOf = function(val) {
		for (var i = 0; i < this.length; i++) {
			if (this[i] == val) { 
				return i;
			}
		}
		return -1;
	};
	Array.prototype.remove = function(val) {
		var index = this.indexOf(val);
		if (index > -1) {
			this.splice(index, 1);
		}
	};
	
	$(document).ready(function() {
		function getContextPath() {
			var contextPath = "";
			if(!isRoot) {
				var pathName = document.location.pathname;
		    	var index = pathName.substring(1).indexOf("/");
		    	contextPath = pathName.substring(0, index + 1);
			}
			return contextPath;
		}
		var body = $(document.body);
		var sys = {
			ctx:getContextPath(),
			desktop:$("<div data-options=\"region:'center'\"></div>").appendTo(body),
			taskbar:$("<div data-options=\"region:'south',split:false\" style=\"height:35px;line-height:35px;\"></div>").appendTo(body),
			contextmenu:null,
			uris:{},
			tasks:{},
			apps:[],
			folders:{},
			appMap:{},
			isInFolder:function(app) {
				return !!this.folders[app.folder];
			},
			addToFolder:function(app, left, top) {
				var folder = this.folders[app.folder];
				if(!folder) {
					//创建文件夹
					var me = this;
					var icon = $('<a href="#" class="desktop-icon">' +
						'<span class="icon"><span class="folder">&nbsp;</span><ul class="icons"></ul></span>' + 
						'<span class="text">'+app.folder+'</span></a>').appendTo(this.desktop);
					var icons = icon.find("ul.icons:first");
					this.folders[app.folder] = folder = {
						apps:[],
						left:left-2,
						top:top-2,
						icons:icons,
						addApp:function(app) {
							this.apps.push(app);
							if(this.apps.length < 9) {
								$('<li><img src="'+ me.ctx + app.icon + '" class="icons" /></li>').appendTo(this.icons);
							}
						},
						addIcons:function(win) {
							var height = 330;
							var iconWidth = 100;
							var iconHeight = 110;
							var iconRows = parseInt(height / iconHeight);
							var top = 0;
							var left = 0;
							for(var i=0; i<this.apps.length; i++) {
								top =  parseInt(i / iconRows) * iconHeight + 5;
								left = (i % iconRows) * iconWidth + 5;
								me.addIcon(win, this.apps[i], left, top);
							}
						},
						open:function() {
							var _this = this;
							var wind = $("<div class='folder'><span class='close'>&nbsp;</span></div>").appendTo(sys.desktop);
							wind.children("span.close").click(function() {
								wind.animate({
								    width:'30px',
									height:'30px'
								}, "fast", function() {wind.remove();});
							});
							var height = $(window).height() - me.taskbar.height();
							var t_top = this.top;
							if(_this.top + 330 > height) {
								t_top = height - 330;
							}
							this.addIcons(wind);
							wind.css({
								left:_this.left,
								top:_this.top,
								width:"30px",
								height:"30px"
							});
							wind.animate({
								top:t_top,
							    width:'330px',
								height:'330px'
							});
						}
					};
					icon.css({
						left:left,
						top:top
					});
					icon.bind("contextmenu", function(e) {
						e.preventDefault();
					});
					icon.click(function() {
						folder.open();
						return false;
					});
				}
				folder.addApp(app);
			},
			addIcon:function(container, app, left, top) {
				var icon = $('<a href="#" class="desktop-icon">' +
					'<span class="icon"><img src="' + this.ctx + app.icon + '" class="icon" /></span>' + 
					'<span class="text">' + app.name + '</span></a>').appendTo(container);
				icon.css({
					left:left,
					top:top
				});
				icon.bind("contextmenu", function(e) {
					e.preventDefault();
				});
				icon.click(function() {
					loadAppJs(app);
					return false;
				});
			},
			addIcons:function(apps) {
				var height = $(window).height() - this.taskbar.height();
				var iconWidth = 100;
				var iconHeight = 110;
				var iconRows = parseInt(height / iconHeight);
				var top = 0;
				var left = 0;
				var index = 0;
				for(var i=0; i<apps.length; i++) {
					if(apps[i].desktop) {
						top =  (index % iconRows) * iconHeight + 5;
						left = parseInt(index / iconRows) * iconWidth + 5;
						if(apps[i].folder) {
							if(!this.isInFolder(apps[i])) {
								index ++;
							}
							this.addToFolder(apps[i], left, top);
						} else {
							this.addIcon(this.desktop, apps[i], left, top);
							index ++;
						}
					}
				}
			},
			refreshIcons:function() {
				this.clearIcons();
				this.addIcons(this.apps);
			},
			clearIcons:function() {
				this.folders = {};
				this.desktop.children("a.desktop-icon").remove();
			},
			background:function(uri) {
				body.css({
					"background-image" : "url(" + sys.ctx + ""+uri+")"
				});
			},
			tensile:function() {
				body.css({
					"background-position" : "",
					"filter" : "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale')",  
					"-moz-background-size" : "100% 100%",  
		    		"background-size" : "100% 100%"
				});
			},
			tile:function() {
				body.css({
					"background-repeat" : "repeat",
					"background-position" : "",
					"filter" : "",  
					"-moz-background-size" : "",  
		    		"background-size" : ""
				});
			},
			center:function() {
				this.tile();
				body.css({
					"background-position" : "center",
					"background-repeat" : "no-repeat"
				});
			}, 
			
			init:function() {
				//初始化桌面
				body.layout();
				var source = '<div class="easyui-menu" style="width:120px;">' +
					'<div data-options="iconCls:\'icon-bgsetting\',name:\'background\'">设置背景</div>' +
					//'<div class="menu-sep"></div>' +
					//'<div data-options="name:\'tile\'">窗口平铺</div>' +
					//'<div data-options="name:\'superposition\'">窗口叠加</div>' +
				'</div>';
				sys.contextmenu = $(source).appendTo(sys.desktop);
				sys.contextmenu.menu({
				    onClick:function(item) {
				        if(item.name == "background") {
				        	loadAppJs({
								id:"usersetting.background",
								name:"桌面设置",
								icon:"/resources/images/icons/background.png",
								uri:"/resources/apps/jquery.easyui.background.js"
								
							});
				        }
				        return false;
				    }
				});
				
				sys.desktop.css({
					"position" : "relative",
					"overflow" : "hidden",
					"background-color" : "transparent"
				});
				
				sys.desktop.bind("contextmenu", function(e) {
					e.preventDefault();
					sys.contextmenu.menu("show", {
						left : e.pageX,
						top : e.pageY
					});
				});
				sys.taskbar.addClass("desktop-taskbar");
				sys.taskbar.css("background-color", "transparent");
				sys.taskbar = $("<div></div>").appendTo(body);
				sys.taskbar.taskbar(72, 48);
				
				document.onMaskShow = function(zIndex) {
					sys.taskbar.css("z-index", zIndex);
				}
				
				document.onMaskHide = function() {
					sys.taskbar.css("z-index", 9999);
				}
				//桌面菜单
				var html = '<nav class="gooey-desktop-menu">' + 
					'<input type="checkbox" class="menu-open" name="menu-open4" id="menu-open4"/>' +
					'<label class="open-button" for="menu-open4">' +
					'<span class="burger burger-1"></span>' +
					'<span class="burger burger-2"></span>' +
					'<span class="burger burger-3"></span>' +
					'</label>' +
					'</nav>';
				var menu = $(html).appendTo(sys.desktop);
				var usersetting = $('<a href="#" class="gooey-menu-item"><i class="fa fa-user fa-lg"></i></a>').appendTo(menu);
				usersetting.click(function() {
					loadAppJs({
						id:"user.mine",
						name:"我的信息",
						icon:"/resources/images/icons/people.png",
						uri:"/resources/apps/jquery.easyui.myaccount.js"
					});
					return false;
				});
				var exit = $('<a href="#" class="gooey-menu-item"><i class="fa fa-power-off fa-lg"></i></a>').appendTo(menu);
				exit.click(function() {
					$.messager.confirm('确认：', '确定要退出系统吗?', function(r){
						if (r){
							window.location.href = sys.ctx + "/login/logout";
						}
					});
					return false;
				});
				menu.gooeymenu({
					bgColor: "#398CFF",
					contentColor: "white",
					style: "vertical",
					vertical: {
						menuItemPosition: "glue",
						direction: "down"
					},
					circle: {
						radius: 90
					},
					margin: "small",
					size: 40,
					bounce: true,
					bounceLength: "small",
					transitionStep: 100,
					hover: "#398CFF"
				});
				
				//背景
				$.post(sys.ctx + "/user/setting/value", {field_name:"background"}, function(setting) {
					sys.setBackgroundBySetting(setting)
				}, "text")
				
			},
			setBackgroundBySetting:function(setting) {
				if(setting == "") {
					sys.background("/resources/images/desktop/default.jpg");
					sys.tensile();
				} else {
					var bg = setting.split("`")
					sys.background(bg[0]);
					switch(bg[1]) {
						case "2":
							sys.tile();
							break;
						case "3":
							sys.center();
							break;
						default:
							sys.tensile();
					}
				}
			}
		}
		sys.init();
		//ajax全局处理
		$(document).ajaxError(function(event, xhr, options){
			if(xhr.status == 403) {
				//禁止访问
				$.messager.alert('提示：','403，禁止访问！', "warning");
			} else if(xhr.status == 203) {
				//未登录
				window.location.href = sys.ctx + "/login/page";
			}
		});
		
		/**
		 * app {id:'应用ID', icon:'应用任务图标', uri:'应用js路径', name:'应用名称'}
		 */
		function loadAppJs(app, appParams) {
			$.get(sys.ctx + app.uri, {}, function(data) {
				var obj = eval("(" + data + ")");
				if(!obj.single || (obj.single && !sys.uris[app.uri])) {
					var config = {
						taskid:uuid.create(),
						ctx:sys.ctx,
						setBackgroundBySetting:function(setting) {
							sys.setBackgroundBySetting(setting)
						},
						hasPermission:function(appId, perm) {
							var t_app = sys.appMap[appId];
							if(t_app) {
								return t_app.perms[perm];
							}
							return false;
						},
						createWindow:function(source, params) {
							var me = this;
							if(me.taskid) {
								var wind = $(source).appendTo(sys.desktop);
								var event = {
									onClose:function() {}
								};
								$.extend(event, params);
								params.inline = true;
								params.onClose = function() {
									event.onClose.call(this);
									var t_tasks = sys.tasks[me.taskid]; 
									t_tasks.remove(wind);
									wind.window("destroy");
									if(t_tasks.length < 1) {
										me._taskbutton.remove();
										delete sys.tasks[me.taskid];
										if(obj.single) {
											sys.uris[app.uri] = false;
										}
									}
								}
								wind.window(params);
								var tasks = sys.tasks[me.taskid]; 
								if(typeof(tasks) == "undefined") {
									tasks = sys.tasks[me.taskid] = [];
									me._taskbutton = $("<img width='48px' src='"+sys.ctx + me.icon + "'/>").appendTo(sys.taskbar);
									me._taskbutton.tooltip({
										position: 'top',
									    content: me.name
									});
									me._taskbutton.bind("contextmenu", function(e) {
										e.preventDefault();
										//右键菜单
									});
									me._taskbutton.click(function() {
										var t_tasks = sys.tasks[me.taskid];
										for(var i=0; i<t_tasks.length; i++) {
											t_tasks[i].window("open");
										}
									});
								} 
								tasks.push(wind);
								return wind;
							}
							return null;
						},
						run:function(appId, params) {
							var t_app = sys.appMap[appId];
							if(t_app) {
								loadAppJs(t_app, params);
							}
						}
					};
					//获取权限
					$.get(sys.ctx + "/manager/permissions", {app_id:app.id}, function(perms) {
						$.extend(config, app);
						config.perms = perms;
						if(obj.single) {
							sys.uris[app.uri] = true;
						}
						obj.launch.call(config, appParams);
					}, "json");
				}
			}, "text");
		}
		
		$.fn.extend({
			row : function(attrs) {
				var me = $(this[0]);
				if(me.is("table") || me.is("tbody")) {
					var row = $('<tr></tr>').appendTo(me);
					if(attrs) {
						row.attr(attrs);
					}
					return row;
				}
				return null;
			},
			tbody : function(attrs) {
				var me = $(this[0]);
				if(me.is("table")) {
					var row = $('<tbody></tbody>').appendTo(me);
					if(attrs) {
						row.attr(attrs);
					}
					return row;
				}
				return null;
			},
			cell : function(content, attrs) {
				var me = $(this[0]);
				if(me.is("tr")) {
					var td = $('<td></td>').appendTo(me);
					if(attrs) {
						td.attr(attrs);
					}
					if(typeof(content) == "string") {
						td.append(content);
					} else {
						content.appendTo(td);
					}
					return td;
				}
				return null;
			}
		});
		
		//读取桌面应用
		$.post(sys.ctx + "/manager/apps", {}, function(json) {
			sys.apps = json;
			$(sys.apps).each(function() {
				sys.appMap[this.id] = this; 
			});
			sys.refreshIcons();
			$(window).resize(function() {
				sys.refreshIcons();
			});
		}, "json");
	});
})(jQuery, false);